# -*- coding: utf-8 -*-

import os
from k8s.env import TEMPLATES_DIR, CONF_DIR, IMAGE_REPO
from conf.jinja2_tool import jinja2_dump
from kubernetes import client, config
from conf.yaml_tool import yaml_load, yaml_dump
from misc.color import INFO, SINFO, CRIT, SUMM, WARN


class PVCClient(object):
    def __init__(self, namespace):
        from log.logger import logger
        self.logger = logger
        self.namespace = namespace
        self.ctx = client.CoreV1Api()

    def create(self, yaml_file):
        msg = "Namespace [%s]: creating Persistent Volume Claim from [%s]" % (self.namespace, yaml_file)
        self.logger.info(msg)
        print(SINFO % ("|--Info: " + msg))

        if os.path.getsize(yaml_file) == 0:
            msg = "skip empty file %s" % yaml_file
            self.logger.error(msg)
            print(WARN % ("  |--Warn: " + msg))
            return

        bodies = yaml_load(yaml_file, all=True)
        if not bodies:
            msg = "failed to load content from %s" % yaml_file
            self.logger.error(msg)
            print(CRIT % ("  |--Error: " + msg))
            return

        for body in bodies:
            try:
                resp = self.ctx.create_namespaced_persistent_volume_claim(namespace=self.namespace, body=body)
                msg = "Namespace [%s]: PersistentVolumeClaim created. name='%s'" % (self.namespace, resp.metadata.name)
                self.logger.info(msg)
                print(INFO % ("  |--Info: " + msg))
            except Exception as e:
                # conflict exception: 409
                if str(e).split()[0] != '(409)':
                    msg = str(e)
                    print(CRIT % ("  |--Error: " + msg))
                else:
                    msg = "instance already exits."
                    print(INFO % ("  |--Info: " + msg))
                self.logger.critical(msg)

    def delete(self, name):
        try:
            resp = client.CoreV1Api().delete_namespaced_persistent_volume_claim(namespace=self.namespace, name=name)
            print("PersistentVolumeClaim deleted. name='%s'" % resp.metadata.name)
        except Exception as e:
            print(e)

    def update(self, yaml_file):
        '''
            暂不支持自动更新pvc
        '''
        pass

    def get(self):
        pass